package com.share.service;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.share.dao.impl.BaseJodisDao;
import com.share.entity.ZookeeperCfg;
import com.share.util.JsonUtils;

/**
 * 
 * <p>Title: BaseRedisService </p>
 * <p>Description: redis操作接口</p>
 */
@Service
public class BaseRedisService{

	@Autowired
	@Qualifier("zkConfigCodis")
	private ZookeeperCfg zookeeperCfg;

	@Autowired
	private BaseJodisDao baseJodisDao;

	private static final Logger LOGGER = Logger.getLogger(BaseRedisService.class);

	/**
	 * Description: 查询
	 */
	@SuppressWarnings("unchecked")
	public <T> T query(String key,Class<T> type){
		try{
			String jsonValue = (String) baseJodisDao.get(key);
			if(jsonValue != null){
				return (T) JsonUtils.fromJson(jsonValue,type);
			}
		}catch(Exception e){
			LOGGER.error(e);
		}
		return null;
	}
	

	/**
	 * Description: 删除
	 */
	public void delete(String key){
		try{
			baseJodisDao.delete(key);
		}catch(Exception e){
			LOGGER.error("BaseRedisService deleteByKey failed:"+e.getMessage());
		}
	}
	

	/**
	 * Description: 添加
	 */
	public <T> boolean add(String key,T t){
		boolean bRet = false;
		try{
			bRet = baseJodisDao.setNx(key,t);
		}catch(Exception e){
			LOGGER.error("BaseRedisService add failed:",e);
		}
		return bRet;
	}
	

	/**
	 * Description: 增加过期时间
	 */
    public Boolean expireAt(String key, Date date){  	
    	for(int i=0;i<3;i++){
    		try{
    			return baseJodisDao.expireAt(key, date);
    		}catch(Exception e){
    			if(i==2){
    				LOGGER.error("BaseRedisService expireAt failed:",e);
    			}
    		}
    		
    	}
    	return false;
    }
    

	/**
	 * Description: 查询过期时间
	 */
    public long ttl(String key){
    	long ttl = 0;
    	try{
    		ttl = baseJodisDao.ttl(key);
    	}catch(Exception e){
    		LOGGER.error("BaseRedisService ttl failed:",e);
    	}
    	return ttl;
    }
    
    /**
	 * Description: 执行lua脚本
	 */
    public void excuteLua(List<String> keys, List<String> values){
    	try{
    		baseJodisDao.excuteLua(keys, values);
    	}catch(Exception e){
    		LOGGER.error("BaseRedisService ttl failed:",e);
    	}
    }
	
}